package com.jstyle.jclifexd.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.security.ProviderInstaller;
import com.jstyle.jclifexd.NetWork.NetWorkUtil;
import com.jstyle.jclifexd.R;
import com.jstyle.jclifexd.adapter.SearchAdapter;
import com.jstyle.jclifexd.model.Search;
import com.jstyle.jclifexd.model.googleinfo.ResultRoot;
import com.jstyle.jclifexd.model.googleinfo.SeachResultRoot;
import com.jstyle.jclifexd.utils.Utils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * google搜索附近地理位置信息
 */

public class GoogleSeachAtivity extends BaseActivity implements OnMapReadyCallback ,GoogleApiClient.ConnectionCallbacks{
    @BindView(R.id.googlemap_local)
    com.google.android.gms.maps.MapView mapView;
    @BindView(R.id.map_list)
    RecyclerView mapList;
    @BindView(R.id.EditText_seach)
    EditText EditText_seach;
    GoogleMap mygoogleMap;
    private LatLng latlng;
    private SearchAdapter adapter;
    String date = "";
    private GoogleApiClient mGoogleApiClient;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.getWindow().setType(WindowManager.LayoutParams.TYPE_APPLICATION_PANEL);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        this.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        setContentView(R.layout.activity_googlelocal);
        Double lat=  Double.valueOf(getIntent().getStringExtra("Latitude"));
        Double log=  Double.valueOf(getIntent().getStringExtra("Longitude"));
        latlng=new LatLng(lat,log);
        ButterKnife.bind(this);
        mapView.onCreate(savedInstanceState);
        init();
        adapter = new SearchAdapter(GoogleSeachAtivity.this);
        LinearLayoutManager aa = new LinearLayoutManager(this);
        aa.setOrientation(LinearLayoutManager.VERTICAL);
        mapList.setLayoutManager(aa);
        mapList.setAdapter(adapter);
        adapter.setOnItemClickListener(new SearchAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(Search aa, int position) {
                date = aa.getName() + "," + aa.getInfo();
            }
        });

    }

    @OnClick({R.id.iv_back, R.id.create_nextstep,R.id.ok})
    public void onViewClicked(View view) {
        if (Utils.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.ok:
                if(TextUtils.isEmpty(EditText_seach.getText())){
                    return;
                }
                Seachinfo(EditText_seach.getText().toString());
                break;
            case R.id.iv_back:
                finish();
                break;
            case R.id.create_nextstep:
               if(TextUtils.isEmpty(date)){
                   showToast(getResources().getString(R.string.select_location));
                   return;
               }
                Intent intent=new Intent();
                intent.putExtra("date",date);
                setResult(6543,intent);
                finish();
                break;

        }
    }

    private void init() {
        mapView.onResume();

        try {
            MapsInitializer.initialize(GoogleSeachAtivity.this);
        } catch (Exception e) { e.printStackTrace(); }

        int errorCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(GoogleSeachAtivity.this);

        if (ConnectionResult.SUCCESS != errorCode) {
            GooglePlayServicesUtil.getErrorDialog(errorCode,
                    GoogleSeachAtivity.this, 0).show();
        } else {
            mapView.getMapAsync(GoogleSeachAtivity.this);
        }

    }






    //-------- 定位 End ------

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }


    @Override
    public void onMapReady(GoogleMap googleMap) {
        mygoogleMap=googleMap;
        mygoogleMap.getUiSettings().setAllGesturesEnabled(true);

        Settingmarlet(latlng);
        GetmapInfo(latlng);
        mygoogleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                Settingmarlet(latLng);
                GetmapInfo(latLng);
            }
        });
    }




    private void GetmapInfo(final LatLng latLng){
        Map<String, Object> map = new HashMap<>();
        map.put("location",latLng.latitude+","+latLng.longitude);
        map.put("rankby","distance");
        map.put("type","food");
        map.put("key",getString(R.string.API_KEY));
        NetWorkUtil.getInstance().getJstyleApi().googleSeach(map).
                subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<ResultRoot>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(ResultRoot activitvtiesData) {
                if(null!=activitvtiesData){
                    List<Search> myDetails = new ArrayList<>();
                    myDetails.clear();
                    for (int i = 0; i < activitvtiesData.getResults().size(); i++) {
                        if (!TextUtils.isEmpty(activitvtiesData.getResults().get(i).getName()) && !TextUtils.isEmpty(activitvtiesData.getResults().get(i).getVicinity())) {
                            Search search = new Search();
                            search.setCheck(false);
                            search.setName(activitvtiesData.getResults().get(i).getName());
                            search.setInfo(activitvtiesData.getResults().get(i).getVicinity());
                            myDetails.add(search);
                        }
                    }
                    adapter.SetData(myDetails);
                }
            }
            @Override
            public void onError(Throwable e) {
            }
            @Override
            public void onComplete() {
            }
        });
    }

    private void Seachinfo(String input){
        Map<String, Object> map = new HashMap<>();
        map.put("address",input);
        map.put("key",getString(R.string.API_KEY));
        NetWorkUtil.getInstance().getJstyleApi().googleInputSeach(map).
                subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<SeachResultRoot>() {
            @Override
            public void onSubscribe(Disposable d) {
            }
            @Override
            public void onNext(SeachResultRoot activitvtiesData) {
                if(null!=activitvtiesData){
                    List<Search> myDetails = new ArrayList<>();
                    myDetails.clear();
                    for (int i = 0; i < activitvtiesData.getResults().size(); i++) {
                        if (!TextUtils.isEmpty(activitvtiesData.getResults().get(i).getAddress_components().get(0).getLong_name()) && !TextUtils.isEmpty(activitvtiesData.getResults().get(i).getFormatted_address())) {
                            Search search = new Search();
                            search.setCheck(false);
                            search.setName(activitvtiesData.getResults().get(i).getAddress_components().get(0).getLong_name());
                            search.setInfo(activitvtiesData.getResults().get(i).getFormatted_address());
                            myDetails.add(search);
                        }
                    }
                    adapter.SetData(myDetails);
                }
            }
            @Override
            public void onError(Throwable e) {
            }
            @Override
            public void onComplete() {
            }
        });
    }


    private void Settingmarlet(LatLng latlng){
        mygoogleMap.clear();
        Bitmap bitmap=BitmapFactory.decodeResource(getResources(),R.drawable.map_right).copy(Bitmap.Config.ARGB_8888, true);
        mygoogleMap.addMarker(new MarkerOptions().position(latlng).icon(BitmapDescriptorFactory.fromBitmap(bitmap)));
        mygoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latlng, 16));
        getLocationList();
    }


    private void getLocationList() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        //创建GoogleAPIClient实例
        if (mGoogleApiClient == null) {
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addConnectionCallbacks(GoogleSeachAtivity.this)
                    .addApi(LocationServices.API)
                    .build();
        }

    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {

    }

    @Override
    public void onConnectionSuspended(int i) {

    }
}